package com.lcd.ssm.service.impl;

import com.lcd.ssm.domain.Employee;
import com.lcd.ssm.domain.Role;
import com.lcd.ssm.mapper.EmployeeMapper;
import com.lcd.ssm.page.PageResult;
import com.lcd.ssm.query.EmployeeQueryObject;
import com.lcd.ssm.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;


    @Override
    public int deleteByPrimaryKey(Long id) {
        return employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(Employee record) {
        int insert = employeeMapper.insert(record);
        List<Role> roles = record.getRoles();
        for (Role role : roles) {
            employeeMapper.insertRelationRoles(record.getId(), role.getId());
        }

        return insert;
    }

    @Override
    public Employee selectByPrimaryKey(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> selectAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public int updateByPrimaryKey(Employee record) {
        int i = employeeMapper.updateByPrimaryKey(record);
        //删除旧的关系，添加新的关系
        employeeMapper.deleteRelationWithRole(record.getId());
        List<Role> roles = record.getRoles();
        for (Role role : roles) {
            employeeMapper.insertRelationRoles(record.getId(), role.getId());
        }
        return i;
    }

    @Override
    public Employee getEmployeeForLogin(String username, String password) {
        return employeeMapper.getEmployeeForLogin(username,password);
    }

    @Override
    public PageResult queryForPage(EmployeeQueryObject qo) {
        Long count=employeeMapper.queryForPageCount(qo);
        if (count == 0) {
            return new PageResult(0, Collections.emptyList());
        }
        List<Employee> list=employeeMapper.queryForPage(qo);
        return new PageResult(count.intValue(),list);
    }

    @Override
    public void updateStateByPrimaryKey(Long id) {
        employeeMapper.updateStateByPrimaryKey(id);
    }

    @Override
    public List<Long> queryRoleIdByEmployeeId(Long eid) {
        return employeeMapper.queryRoleIdByEmployeeId(eid);
    }

    @Override
    public List<String> findPermissionStrByEmployeeId(Long id) {
        return employeeMapper.findPermissionStrByEmployeeId(id);
    }
}
